var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api;
var _height = api.config.height-132,_width = api.config.width-34;//获取弹出框弹出宽、高
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'common/kpi/list';

var Utils = {
	doQueryReward:function(rowid){
		commonDia = $.dialog({
			title : '选择奖励',
			content : 'url:'+config.BASEPATH+'sys/reward/to_list_dialog',
			data : {multiselect:false},
			width : 460,
			height : 340,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : "请选择奖励！"});
					return false;
				}
				$("#gridDetail").jqGrid('setRowData', rowid, {reward_name:selected.rw_name,ks_rw_code:selected.rw_code});
				return true;
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#gridDetail").jqGrid('setRowData', rowid, {reward_name:selected.rw_name,ks_rw_code:selected.rw_code});
				}
			},
			cancel:true
		});
	}
};


var handle = {
	loadData:function(data){
		var pdata = {};
		pdata.id=data.ki_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="新增">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-reward" title="奖励">&#x3435;</i>';
		html_con += '</div>';
		return html_con;
	}
};


function existRepeat(){
	var ids = $("#gridDetail").jqGrid('getDataIDs');
	var rowData1 = null;
	var rowData2 = null;
	var leftMax = 0;
	var rightMin = 0;
	for(var i=0;i<ids.length;i++){
		for(var j=i+1;j<ids.length;j++){
			rowData1 = $('#gridDetail').jqGrid('getRowData', ids[i]);
			rowData2 = $('#gridDetail').jqGrid('getRowData', ids[j]);
			leftMax = Math.max(parseFloat(rowData1.ks_min),parseFloat(rowData2.ks_min));
			rightMin = Math.min(parseFloat(rowData1.ks_max),parseFloat(rowData2.ks_max))
			if(leftMax<rightMin){
				return true;
			}
		}
	}
	return false;
}


function ok_Click(){
	var rowId = $('#grid').jqGrid('getGridParam','selrow');
	if(rowId == null || rowId == ''){
		Public.tips({type: 2, content : '您未选择任何数据！'});
		return false;
	}
	var rowData = $('#grid').jqGrid('getRowData', rowId);
	var ids = $("#gridDetail").jqGrid('getDataIDs');
	if(ids == null || ids == '' || ids.length == 0){
		Public.tips({type: 2, content : '请设置KPI指标区间和分数！'});
		return false;
	}
	for(var i=0;i < ids.length;i++){
		var detailRowData = $('#gridDetail').jqGrid('getRowData', ids[i]);
		if(detailRowData.ks_min == '' || detailRowData.ks_max == '' || detailRowData.ks_score == ''){
			Public.tips({type: 2, content : '区间下限、区间上限或分数不能为空！'});
			return false;
		}
	}
	var repeat = existRepeat();
	if(repeat){
		Public.tips({type: 2, content : '区间范围存在交集，请修改！'});
		return false;
	}
	var kpiscores = [];
	for (var i = 0; i < ids.length; i++) {
		var detailRowData = $('#gridDetail').jqGrid('getRowData', ids[i]);
		var kpiscore = {};
		kpiscore.ks_min = detailRowData.ks_min;
		kpiscore.ks_max = detailRowData.ks_max;
		kpiscore.ks_score = detailRowData.ks_score;
		kpiscore.ks_rw_code = detailRowData.ks_rw_code;
		kpiscores.push(kpiscore);
    }
	
	var params = {};
	params.ki_code = rowData.ki_code;
	params.kpiscores = Public.encodeURI(JSON.stringify(kpiscores));
	$.ajax({
		type:"POST",
		url:config.BASEPATH+"sys/kpi/save",
		data:params,
		cache:false,
		dataType:"json",
		success:function(data){
			if(undefined != data && data.stat == 200){
				handle.loadData(data.data);
				api.close();
			}else{
				Public.tips({type: 1, content : data.message});
			}
		}
	});
	return false;
}


var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initGridList();
		this.initEvent();
	},
	initDom:function(){
		this.maxId = 0;
		this.selectRow = {};
	},
	initGrid:function(){
		var colModel = [
			{label:'编号',name: 'ki_code', index: 'ki_code', width: 60},
	    	{label:'名称',name: 'ki_name', index: 'ki_name', width: 80},
	    	{label:'备注',name: 'ki_remark', index: 'ki_remark', width: 140,title:true}
	    ];
		$('#grid').jqGrid({
            url:queryurl,			
			datatype: 'json',
			width: 350,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:30,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			scroll: 1,//是否滚动
			jsonReader: {
				root: 'data',
				repeatitems : false,
				id: 'ki_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").jqGrid('getDataIDs');
				if(ids.length > 0){
					$("#grid tr:eq(1)").trigger("click");
				}else{
					$("#gridDetail").jqGrid("clearGridData");
				}
			},
			loadError: function(xhr, status, error){		
			},
			onCellSelect:function(rowid,iRow,iCol,e){
				var rowData = $("#grid").jqGrid("getRowData",rowid);
				$("#gridDetail").jqGrid("clearGridData").trigger("reloadGrid");
			}
	    });
	},
	addEmptyData:function(){
    	var emptyData = {ks_min:'',ks_max:'',ks_score:''};
    	$("#gridDetail").addRowData(THISPAGE.maxId, emptyData);
    	THISPAGE.maxId = THISPAGE.maxId + 1;
	},
	initGridList: function () {
    	var self=this;
        var colModel = [
            {label:'操作',name:'operate', width: 60, fixed:true, formatter: handle.operFmatter, sortable:false},
            {label:'区间下限',name: 'ks_min',index: 'ks_min',width: 70,align:'right',editable:true,formatter: PriceLimit.formatMoney},
            {label:'区间上限',name: 'ks_max',index: 'ks_max',width: 70,align:'right',editable:true,formatter: PriceLimit.formatMoney},
            {label:'分数',name: 'ks_score',index: 'ks_score',width: 70,align:'right',editable:true},
            {label:'奖励',name: 'reward_name',index: 'reward_name',width: 100,title:true},
            {label:'',name: 'ks_rw_code',index: 'ks_rw_code',width: 0,hidden:true}
        ];
        $("#gridDetail").jqGrid({
            datatype: 'local',
            height: _height,
			width:430,
            colModel: colModel,
            rownumbers: true,
            rowNum: 999,
            pgbuttons:true,
            pager: '#pageDetail',
            recordtext:'{0} - {1} 共 {2} 条',
            gridview: true,//false构造一行数据后添加到grid中
            multiselect:false,//多选
            shrinkToFit: false,//ture，则按比例初始化列宽度
            forceFit: false,//调整列宽度会改变表格的宽度  shrinkToFit 为false时，此属性会被忽略
            viewrecords: true,//是否要显示总记录数信息            
            scroll:1,
            cellEdit: true,
            cellsubmit: 'clientArray',
            jsonReader: {
            	root: 'data',
				repeatitems : false
            },
            loadComplete: function (data) {
            	var ids = $("#gridDetail").jqGrid('getDataIDs');
        		if(ids.length == 0){
					THISPAGE.maxId = 1;
	            	THISPAGE.addEmptyData();
				}else{
					THISPAGE.maxId = 1;
					for(var i=0;i<ids.length;i++){
						if(parseInt(ids[i])>THISPAGE.maxId){
							THISPAGE.maxId = parseInt(ids[i]);
						}
					}
					THISPAGE.maxId = THISPAGE.maxId + 1;
				}
            },
            loadError: function (xhr, st, err) {

            },
            formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(self.selectRow.value == value){
					return value;
				}
				if(value == '' || isNaN(value)){
					Public.tips({type: 2, content : '请输入数字！'});
					return self.selectRow.value;
				}
				if(parseFloat(value).toFixed(2).length > 11 || Math.abs(parseFloat(value)) > 1e+11){
					return self.selectRow.value;
				}
				var rowData = $("#gridDetail").jqGrid("getRowData", rowid);
				if(cellname == 'ks_min'){
					if(parseFloat(value)>parseFloat(rowData.ks_max)){
						Public.tips({type: 2, content : '区间下限不能大于区间上限！'});
						return self.selectRow.value;
					}
					return parseFloat(value).toFixed(2);
				}else if(cellname == 'ks_max'){
					if(parseFloat(value)<parseFloat(rowData.ks_min)){
						Public.tips({type: 2, content : '区间上限不能大于区间下限！'});
						return self.selectRow.value;
					}
					return parseFloat(value).toFixed(2);
				}else if(cellname == 'ks_score'){
					return parseInt(value);
				}
				return value;
			}
        });
    },
    reloadData:function(){
    	var params = 'searchContent='+Public.encodeURI($("#SearchContent").val());
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+params}).trigger("reloadGrid");
	},
	initEvent:function(){
		
		$('#SearchContent').on('keyup',function(){
			if (event.keyCode==13){
				$('#btn-search').click();
			}
		});
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			THISPAGE.reloadData();
		});
		
		$('#gridDetail').on('click', '.operating .ui-icon-plus', function (e) {
            e.preventDefault();
            THISPAGE.addEmptyData();
        });
		$('#gridDetail').on('click', '.operating .ui-icon-trash', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            var ids = $("#gridDetail").jqGrid('getDataIDs');
        	$.dialog.confirm('数据删除后将不能恢复，请确认是否删除？',function(){
        		$('#gridDetail').jqGrid('delRowData', id);
        		if(ids.length==1){
        			THISPAGE.addEmptyData();
        		}
        	});
        });
		$('#gridDetail').on('click', '.operating .ui-icon-reward', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            Utils.doQueryReward(id);
        });
	}
};

THISPAGE.init();